﻿namespace Framework.WebApi.Authentication
{
	public static class AuthenticationJwtBearerExtension
	{
		/// <summary>
		/// Authentication Jwt配置
		/// </summary>
		/// <param name="serviceCollection"></param>
		/// <param name="assemblyList"></param>
		public static void AddAuthenticationJwtBearer(this IServiceCollection serviceCollection)
		{
			// 获取框架上下文
			_ = JWTEncryption.GetFrameworkContext(Assembly.GetCallingAssembly());

			// 添加默认授权
			AuthenticationBuilder authenticationBuilder = serviceCollection.AddAuthentication(options =>
			{
				options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
				options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
			});

			// 添加授权
			authenticationBuilder.AddJwtBearer(o =>
			{
				// 获取Jwt配置
				JWTSettingsOptions jwtSettings = new();
				AppSettings.Bind("JwtSettings", jwtSettings);
				o.TokenValidationParameters = JWTEncryption.CreateTokenValidationParameters(jwtSettings);
			});

			//启用全局授权
			authenticationBuilder.Services.Configure<MvcOptions>(options =>
			{
				options.Filters.Add(new AuthorizeFilter());
			});
		}
	}
}
